package com.huangliusong.web.config;

import com.huangliusong.web.http.converter.properties.PropertiesHttpMessageConverter;
import com.huangliusong.web.method.suport.PropertiesHandlerMerhodArgumentResolver;
import com.huangliusong.web.method.suport.PropertiesHandlerMethodReturnValueHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangliusong
 * @since 2018/10/4
 * {@link }
 */
@Configuration
public class RestWebMvcCofigurer implements WebMvcConfigurer {
    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void init(){
        List<HandlerMethodArgumentResolver> resolvers= requestMappingHandlerAdapter.getArgumentResolvers();
        List<HandlerMethodArgumentResolver> newResolvers=new ArrayList<>(resolvers.size()+1);
        newResolvers.add(new PropertiesHandlerMerhodArgumentResolver());
        newResolvers.addAll(resolvers);
        requestMappingHandlerAdapter.setArgumentResolvers(newResolvers);
        //获取当前HandlerMethodReturnValueHandler
        List<HandlerMethodReturnValueHandler> handlers=requestMappingHandlerAdapter.getReturnValueHandlers();
        List<HandlerMethodReturnValueHandler> newHandlers=new ArrayList<>(handlers.size()+1);
        newHandlers.add(new PropertiesHandlerMethodReturnValueHandler());
        newHandlers.addAll(handlers);
        requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers);
    }
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
       // converters.add(new PropertiesHttpMessageConverter());
        converters.set(0,new PropertiesHttpMessageConverter());
    }


    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        //添加自定义的参数 优先级低于内建的实现
       if (resolvers.size()>0){
           resolvers.set(0,new PropertiesHandlerMerhodArgumentResolver());
       }else{
           resolvers.add(new PropertiesHandlerMerhodArgumentResolver());
       }

    }

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*");
    }
}
